// ignore_for_file: prefer_typing_uninitialized_variables

/*
 * @Author: CodeHare
 * @Date: 2023-09-19 18:46:23
 * @LastEditors: yangni 920556271@qq.com
 * @LastEditTime: 2024-03-04 10:49:38
 * @Description: 电池保护参数设置
 */
// ignore_for_file: unnecessary_overrides, avoid_print
import 'dart:async';

import 'package:get/get.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/ems/rectangle_ems_romote_control/rectangle_battery_protection_parameter/rectangle_battery_protection_parameter_model.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/ems/rectangle_ems_romote_control/rectangle_control_instruct/rectangle_control_instruct_controller.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/utils/func_utils.dart';
import 'package:yt_devops/utils/socket/use_subscribe.dart';

class RectangleBatteryProtectionParameterController extends GetxController {
  RectangleBatteryProtectionParameterModel model =
      RectangleBatteryProtectionParameterModel();
  DeviceServices deviceServices = Get.find<DeviceServices>();
  RectangleControlInstructController controlInstructController =
      Get.find<RectangleControlInstructController>();

  /// 请求参数
  var requestParams;
  bool noPass = true;

  /// 设备 ID
  int? deviceId;
  bool pass = false;

  /// 订阅 websocket
  UseSubsribe subscribe = UseSubsribe();
  StreamSubscription<Map<String, dynamic>>? subscription;
  late Stream<Map<String, dynamic>> broadcastStream;

  @override
  void onInit() {
    super.onInit();
    deviceId = Get.arguments['deviceId'];
    model.parameterMap = model.generateParameterList();

    broadcastStream =
        subscribe.start([deviceId!], true).stream.asBroadcastStream();

    subscription = broadcastStream.listen((data) {
      model.socketMap = data;
      initBatteryProtection();
      update();
    });
  }

  /// @description: 初始化组件
  /// @return {*}
  void initBatteryProtection() {
    model.socketMap.forEach((key, value) {
      if (key == 'OverchargeProtection') {
        model.overchargeProtection.text = value.toString();
      } else if (key == 'OverchargeRelease') {
        model.overchargeRelease.text = value.toString();
      } else if (key == 'OverdischargeProtection') {
        model.overDischargeProtection.text = value.toString();
      } else if (key == 'Overrelease') {
        model.overrelease.text = value.toString();
      }
    });
  }

  /// @description: 收集请求参数
  /// @return {*}
  Map<String, dynamic> collectParams() {
    deviceId = Get.arguments['deviceId'];

    var params = {
      /// 设备ID
      "deviceId": deviceId.toString(),

      /// 需要下发key的参数根据serviceId配置
      "input": {
        "OverchargeProtection": model.overchargeProtection.text,
        "OverchargeRelease": model.overchargeRelease.text,
        "OverdischargeProtection": model.overDischargeProtection.text,
        "Overrelease": model.overrelease.text,
      },

      ///服务名称 - 电池保护参数设置
      "serviceId": "setChargeReleaseProtect",
    };

    return params;
  }

  /// @description: 下发指令前处理
  /// @return {*}
  void beforeSendCommand() {
    var i = 0;
    for (var key in model.parameterMap!.keys) {
      final item = model.parameterMap![key]!;
      final text = item.textEditingController.text;

      /// 判空校验失败
      if (text.isEmpty) {
        model.parameterMap![key]!.error =
            "${ResKey.plsInput.tr}${model.parameterMap![key]!.label.trim()}";
      } else {
        /// 通过校验
        i++;
        model.parameterMap![key]!.error = "";
      }
    }

    /// 通过校验的参数数量
    pass = i == model.parameterMap!.keys.length ? true : false;
    update();
  }

  /// @description: 下发指令接口
  /// @return {*}
  Future sendCommand(context) => Configs.httpClient.requestWithLoading(
        () async {
          var params = collectParams();
          await deviceServices.deviceRemoteSetting(params);
          FuncUtils.requestTipsDislog(context, ResKey.executeSuccess.tr, true);
          update();
        },
        onError: (err) {
          FuncUtils.requestTipsDislog(context, ResKey.executeFailure.tr, false);

          Future.delayed(
            const Duration(
              milliseconds: 1000,
            ),
            () => Get.back(),
          );
          return true;
        },
      );

  @override
  void onClose() {
    super.onClose();

    /// 清除控制器
    model.overchargeProtection.clear();
    model.overchargeRelease.clear();
    model.overDischargeProtection.clear();
    model.overrelease.clear();

    /// 关闭通道
    subscription!.cancel();
    subscribe.close();
  }
}
